<?php

namespace app\controller;

use app\exception\RequestException;
use app\model\Discount;
use app\model\Line as LineModel;
use think\Request;

class Line extends BaseController
{
    public function lists(): \think\Paginator
    {
        return LineModel::field('id, name, price, created_time')
            ->order('id', 'desc')
            ->paginate();
    }

    public function checkNameExists($name, $id = 0): bool
    {
        $model = LineModel::field('id')
        ->where('name', $name)
        ->when($id, function($query) use ($id) {
            $query->where('id', '<>', $id);
        })
        ->find();

        return (bool)$model;
    }

    public function save(Request $request)
    {
        $param = $request->post();
        $rule  = [
            'name'  => 'require|max:100',
            'price' => 'require|float|min:0',
        ];
        $this->validate($param, $rule);

        if ($this->checkNameExists($param['name'], $param['id'] ?? 0)) {
            throw new RequestException('线路名称重复！');
        }
        if (!empty($param['id'])) {
            $model = LineModel::where('id', $param['id'])->find();
            if (!$model) {
                throw new RequestException('非法访问！');
            }
        } else {
            $model = new LineModel;
        }
        $model->name  = $param['name'];
        $model->price = $param['price'];
        $model->save();
    }

    public function del($id)
    {
        $model = LineModel::where('id', $id)->find();
        if (!$model) {
            throw new RequestException('非法访问！');
        }
        $model->delete();
    }

    public function userUsableList($userId)
    {
        $q = Discount::fieldRaw('1')
            ->where('user_id', $userId)
            ->whereRaw('line_id = cs_line.id')
            ->fetchSql(true)
            ->select();

        return LineModel::field('id, name, price')
            ->whereNotExists($q)
            ->order('id', 'desc')
            ->select();
    }

    public function userDiscountList($userId)
    {
        return Discount::where('user_id', $userId)
            ->field('id, discount, line_id, created_time')
            ->with(
                [
                    'line' => function ($query) {
                        $query->field('id, name, price');
                    }
                ]
            )
            ->order('id', 'desc')
            ->paginate();
    }

    public function bindDiscount(Request $request)
    {
        $param = $request->post();
        $rule  = [
            //'userId'   => 'require|integer',
            //'lineId'   => 'require|integer',
            'discount' => 'require|float|min:0|max:100',
        ];
        $this->validate($param, $rule);
        
         if (empty($param['id'])) { 
             $exists = Discount::field('id')
            ->where('user_id', $param['userId'])
            ->where('line_id', $param['lineId'])
            ->find();
            if ($exists) {
                throw new RequestException('该用户已存在该线路优惠！');
            }
             $model           = new Discount;
            $model->userId   = $param['userId'];
            $model->lineId   = $param['lineId'];
         } else {
            $model = Discount::find($param['id']);
         }
        $model->discount = $param['discount'];
        $model->save();
    }

    public function unbindDiscount($id)
    {
        $model = Discount::where('id', $id)->find();
        if (!$model) {
            throw new RequestException('非法访问！');
        }
        $model->delete();
    }
}
